const Joi= require('joi');
const helmet=require('helmet');
const morgan=require('morgan');
const express = require('express');
const app = express();

const port = 3000;
const nums = [
    { id: 1, name: "hewei1" },
    { id: 2, name: "hewei2" },
    { id: 3, name: "hewei3" }
]
app.use(express.json());//打开获取请求体JSON对象
app.use(express.urlencoded({}));// 传递表单数据
app.use(express.static('public'));// 传递文本图片
app.use(helmet());

if(app.get('env')==='development'){
    app.use(morgan('tiny'));
    console.log('开发环境下记录日志')
}

app.use(function(req,rex,next){
    console.log('登陆中');
    next();
});

app.use(function(req,rex,next){
    console.log('验证');
    next();
});


const url='/api/:id';
app.get('/', (req, res) => {
    res.send('Hellp World!!!');
});
//读取
app.get(url, (req, res) => {
    const id=nums.find(x=> x.id===parseInt(req.params.id));
    if(!id) return res.status(404).send("找不到此文件");
    res.send(id.name);
});
//新增
app.post('/api',(req,res)=>{
    const {error} = validateCourse(req.body);
    if(error) return res.status(400).send(result.error.details[0].message);//报错误信息

    const course={
        id:nums.length + 1,
        name:req.body.name
    }
    nums.push(course);
    console.log(nums);
    res.send(nums);
});
//更新
app.put(url,(req,res)=>{
    const id=nums.find(x=> x.id===parseInt(req.params.id));
    if(!id) return res.status(404).send("找不到此文件");

    const {error} = validateCourse(req.body);
    if(error) return res.status(400).send(result.error.details[0].message);



    id.name=req.body.name;
    res.send(id)
    // console.log(nums);
})

app.delete(url,(req,res)=>{
    const id=nums.find(x=> x.id===parseInt(req.params.id));
    if(!id) return res.status(404).send("找不到此文件");

    //Delete
    const index=nums.indexOf(id);
    nums.splice(index,1);
    console.log(nums);
    res.send(id);


})

function validateCourse(course){
    const schema={
        // 是个字符串，长度最少为3 必须为字段
        name:Joi.string().min(3).required()
    };
    return Joi.validate(course,schema);

}

app.listen(port, () => console.log(`正在监听${port}端口`));